import {
  cutpriceHome,
  cutpriceCut,
  productsFeatured,
  addFormId,
  createQrcode,
  createCutpriceQrcode,
  cutRegle,
  detailLog,
  getBeShared,
} from "../../../api.js"
var app = getApp().globalData
Page({
  data: {
    form: [],
    header_pic: "",
    countDay: '',
    countDownHour: '',
    countDownMinute: '',
    countDownSecond: "",
    interested_list: [],
    alert_none: false,
    alert_erwei: '',
    shar_bj: '',
    topimageurl: '',
    alert_upType: '',
    many_alert:false,
    alert_num:'',
    rule_text:[],
    ruler_alert:false,
    hide:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      options
    })
    console.log(options)
    cutRegle().then(res =>{
      console.log(res)
      this.setData({
        rule_text: res.data.data.regle
      })
    })
    if (options.enter_type){
      var num = parseInt(options.position) + 1
      detailLog(app.businessId, app.Store.token, options.id, options.enter_type, options.label, num).then(res =>{
        console.log(res)
      })
    }
  },
  close_ruler(){
    this.setData({
      ruler_alert:false
    })
  },
  onShow: function(options) {
    getApp().startpage(new Date().getTime())
    this.initialization(this.data.options)
    this.recommend(this.data.options)
  },
  //推荐列表砍价
  goactiv(e){
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index + 1
    console.log(this.data.options)
    var that = this
    that.data.options.id = id
    that.setData({
      'options.id': id
    })
    wx.pageScrollTo({
      scrollTop: 0
    })
    detailLog(app.businessId, app.Store.token, id, 7, 2, index).then(res => {
      console.log(res)
    })
    that.initialization(that.data.options)
  },
  // 页面初始化
  initialization(options) {
    var that = this
    cutpriceHome(app.Store.token, options.id).then(res => {
      if (res.data.code == 666) {
        that.countDown(res.data.data.time.activity_end_time, res.data.data.time.now)
        if (res.data.data.is_in == 0) {
          cutpriceCut(app.Store.token, options.id).then(res => {
            if (res.data.code == 666) {
              that.setData({
                many_alert:true,
                alert_num: res.data.data.cut_price,
                hide: false
              })
              that.initialization(that.data.options)
            }
          })
        } else {
          that.setData({
            form: res.data.data,
            header_pic: app.Store.user.topimageurl,
            hide:false
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  golist(){
    wx.navigateTo({
      url: '/pages/activity/list/list',
    })
  },
  //推荐商品
  recommend(options) {
    var that = this
    productsFeatured(app.Store.token, options.id).then(res => {
      console.log(res)
      if (res.data.code == 666) {
        that.setData({
          interested_list: res.data.data
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  onHide: function() {
    getApp().endpage(new Date().getTime())
  },
  // 倒计时
  countDown(endTime, nowTime) {
    var now = new Date(nowTime.replace(/\-/g,"/")).getTime()
    var end_time = new Date(endTime.replace(/\-/g, "/")).getTime()
    var totalSecond = (end_time - now) / 1000
    var interval = setInterval(function() {
      var second = totalSecond;
      var day = Math.floor((second) / 3600 / 24);
      var daStr = day.toString();
      var hr = Math.floor((second) / 3600);
      var hrStr = hr.toString() % 24;
      if (hrStr.length == 1) hrStr = '0' + hrStr;
      var min = Math.floor((second - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;
      var sec = second - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;
      this.setData({
        countDay: daStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        // wx.showToast({
        //   title: '活动已结束',
        // });
        this.setData({
          countDay: '0',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          // jieshu: true
        });
      }
    }.bind(this), 1000);
  },
  //返回首页
  goHome(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    })
  },
  foot_goHome(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    })
  },
  // 定义分享
  form_share(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    getBeShared(app.Store.token,'' ,this.data.options.id).then(res =>{
    })
  },
  // 定义分享
  onShareAppMessage(res) {
    return {
      title: "芮享邀你来砍价，购买奢侈品，最低只要600起",
      imageUrl: this.data.form.cut_product_detail[0].pic_url,
      path: '/pages/activity/orderDetails/orderDetails?parent_id=' + getApp().globalData.Store.user.id + '&product_id=' + this.data.options.id + '&source=2',
    }
  },
  //查看订单
  look_batchcode(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var batchcode = this.data.form.batchcode
    wx.navigateTo({
      url: '/pages/money/detail/detail?batchcode=' + batchcode,
    })
  },
  poster(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var that = this
    createCutpriceQrcode(getApp().globalData.Store.token,'pages/activity/orderDetails/orderDetails',that.data.options.id).then(res => {
      if (res.data.code == 666) {
        that.setData({
          alert_erwei: res.data.data.key
        })
        if (that.data.alert_upType == 0) {
          wx.showLoading({
            title: '正在生成分享图片',
          })
          wx.downloadFile({
            url: 'https://document.growthupup.com/details_poster_bj.png',
            success: function(res) {
              that.setData({
                shar_bj: res.tempFilePath
              })
              wx.downloadFile({
                url: getApp().globalData.Store.user.topimageurl,
                success: function(res) {
                  that.setData({
                    topimageurl: res.tempFilePath,
                  })
                  wx.downloadFile({
                    url: that.data.alert_erwei,
                    success: function(res) {
                      wx.hideLoading()
                      that.setData({
                        alert_erwei: res.tempFilePath,
                        alert_none: true,
                        alert_upType: 1
                      })
                      that.canvasImg()
                    }
                  })
                }
              })
            }
          })
        } else {
          wx.downloadFile({
            url: that.data.alert_erwei,
            success: function(res) {
              wx.hideLoading()
              that.setData({
                alert_erwei: res.tempFilePath,
                alert_none: true,
              })
              that.canvasImg()
            }
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  alert_off() {
    this.setData({
      alert_none: false
    })
  },
  // 分享画布
  canvasImg() {
    const ctx = wx.createCanvasContext('myCanvas');
    const img = this.data.shar_bj;
    const name = app.Store.user.name;
    const erwei = this.data.alert_erwei
    const topimageurl = this.data.topimageurl;
    ctx.save();
    ctx.beginPath();
    ctx.drawImage(img, 0, 0, 269, 406); //里面的参数无非就是图片放置的位置即图片的横纵坐标，图片的宽高
    ctx.draw(true);
    ctx.drawImage(erwei, 205, 13, 50, 50);
    ctx.setFillStyle("#fff");
    ctx.setFontSize(10); //字大小
    ctx.setTextAlign('left'); //是否居中显示，参考点画布中线
    ctx.fillText('芮享一种轻奢生活的新方式', 65, 50); //150:canvas画布宽300，取1/2，中间，280：纵向位置
    ctx.setFontSize(8);
    ctx.setTextAlign('left');
    ctx.fillText(name, 65, 20);
    ctx.draw(true);
    ctx.arc(42 / 2 + 13, 42 / 2 + 15, 42 / 2, 0, Math.PI * 2, false);
    ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
    ctx.drawImage(topimageurl, 13, 15, 46, 46); // 推进去图片，必须是https图片    
    ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    ctx.draw(true);
    ctx.draw(true);
  },
  saveImg() {
    var that = this
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            wx.showToast({
              title: '保存成功',
            })
            that.setData({
              alert_none: false,
            })
          },
          fail: function(res) {}
        })
      }
    })
  },
  //去购买
  go_buy(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    var fomr = this.data.form.cut_product_detail[0]
    let keyArr = Object.keys(fomr)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(fomr[k])
    }
    wx.navigateTo({
      url: '/pages/money/settlement/settlement?product=' + JSON.stringify([map]) + '&order_enter_type=3'
    })
  },
  //砍价成功购买
  go_success_buy(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    var fomr = this.data.form.cut_product_detail[0]
    let keyArr = Object.keys(fomr)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(fomr[k])
    }
    wx.navigateTo({
      url: '/pages/money/settlement/settlement?product=' + JSON.stringify([map]) + '&order_enter_type=4'
    })
  },
  close_alert(){
    this.setData({
      many_alert:false
    })
  },
  may_list(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    wx.navigateTo({
      url: '/pages/activity/myList/myList',
    })
  },
  gotop(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    wx.navigateTo({
      url: '/pages/activity/list/list',
    })
  },
  gotopp(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    wx.switchTab({
      url: '/pages/tabBar/index/index'
    })
  },
  formSubmit_homePage(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    this.setData({
      ruler_alert:true
    })
  },
  act(e){
    console.log('222')
  },
  cat_product(){
    var id = this.data.form.cut_product_detail[0].id
    wx.navigateTo({
      url: '/pages/public/productdetail/productdetail?id='+ id +'&enter_type=9'
    })
  }
})